/**
 * MAIN 
 * to compile this:
 * javac -classpath .;[LIB_PATH]/bluecove-2.1.0.jar bluecast.java
 * e.g.: in Windows with JDK 1.6
cd bluecast
javac -classpath .;lib/bluecove-2.1.0.jar -d bin src/bluecast.java

 *
 * first draft by peter.game@gmail.com  2010-02-21
 */
import javax.bluetooth.*;


public class bluecast {

    /**
     * discover bluetooth device and print out (plain text)
     */
    public static int discover() {

        // my bluetooth device (built-in bluetooth of notebook etc.)
        LocalDevice myDevice = null;
        BlueListener blueListener = null;

        try {
            myDevice = LocalDevice.getLocalDevice();
            System.out.println("My address: " + myDevice.getBluetoothAddress());
            System.out.println("My name   : " + myDevice.getFriendlyName());

            // assume: myDevice is non null
            blueListener = new BlueListener();
            DiscoveryAgent agent = myDevice.getDiscoveryAgent();
            agent.startInquiry(DiscoveryAgent.GIAC, blueListener);
        } catch (Exception e) {  // BluetoothStateException
            System.err.println("ex: " + e);
            return -1;
        }

        if (blueListener==null) {
            return -3;
        }

        // assume blueListener is non-null

        // this is a forced wait
        try {
            synchronized(blueListener){
                //timeout  for 30 seconds
        	System.out.println("--before wait--");
                blueListener.wait(30000);
        	System.out.println("--after wait--");
            }
        } 
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        

        return 0;
    }


    public static int testMyBluetooth() {
        LocalDevice myDevice = null;
        BlueListener blueListener = null;
        MyBluetooth myBlue = null;

        try {
            myDevice = LocalDevice.getLocalDevice();
            myBlue = new MyBluetooth(myDevice);
            System.out.println("my address:" + myBlue.address
            + "   name:" + myBlue.friendlyName);

            myBlue.startInquiry();
            myBlue.waitInquiry();

            System.out.println("total remote: " + 
                myBlue.remoteDeviceList.size());

            myBlue.startServiceSearch();

            // TODO: how to wait for the remaining service search???
            Thread.sleep(60000);

            System.out.println("obexDevice size=" 
            + myBlue.obexDeviceList.size());


        } catch (Exception e) {

            System.err.println("testMyBluetooth ex: " + e);
        }
        return 0;
    }

    public static void main(String arg[]) {
        System.out.println("----- bluecast STARTED -----");
        testMyBluetooth();
        // discover();

        System.out.println("----- bluecast ENDED -----");
    }
}
